#include "goods.h"
#include "ui_goods.h"

#include <QMessageBox>
#include <QSqlError>
goods::goods(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::goods)
{
    ui->setupUi(this);
    setWindowTitle("仓库货物管理");

    model1= new QSqlTableModel(this);
    model1->setTable
            ("goods");
    model1->select();
    model1 -> setEditStrategy(QSqlTableModel::OnManualSubmit);

    ui->tableView->setModel(model1);
}

goods::~goods()
{
    delete ui;
}

void goods::on_SearchAll_clicked()
{
    model1->setTable("goods");
    model1->select();
}

void goods::on_add_clicked()
{
    int addrow = model1->rowCount();
    int id = addrow+1;
    model1->insertRow(addrow);
    model1->setData(model1->index(addrow,0),id);
    model1->submitAll();
}

void goods::on_delete_2_clicked()
{
    int currow = ui->tableView->currentIndex().row();//确定行数
     model1->removeRow(currow);
     int issure = QMessageBox::warning(this,tr("删除提醒"),
                                    tr("确认要删除当前行吗？"),
                                       QMessageBox::Yes,QMessageBox::No);
     if(issure==QMessageBox::No){
         model1->revertAll();
     }
     else{
         model1->submitAll();
     }
}



void goods::on_ok_clicked()
{
    model1->database().transaction();
       if(model1->submitAll()){
           if(model1->database().commit()){
               QMessageBox::information(this,"提交提醒","修改成功");
           }
       }
       else{
           model1->database().rollback();
           QMessageBox::information(this,"提交提醒",tr("提交错误1%")
            .arg(model1->lastError().text()),QMessageBox::Yes);
       }
}

void goods::on_search_clicked()
{
    int i = ui->comboBox->currentIndex();
    QString str = ui->lineEdit->text();
    switch (i) {
    case 0:
        model1->setFilter(QString("id = '%1'").arg(str));
        model1->select();
        break;
    case 1:
        model1->setFilter(QString("name = '%1'").arg(str));
        model1->select();
        break;
    }
}

